package com.user.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBUtil {


    public static Connection connection = null;
    public static PreparedStatement preparedStatement = null;
    public static ResultSet resultSet = null;

    //处理preparedStatement语句
    public static PreparedStatement createPreParedStatement(String sql, Object[] params) throws SQLException {
        connection = C3P0Util.getConnection();
        preparedStatement = connection.prepareStatement(sql);

        if (params != null)
            for (int i = 0; i < params.length; i++) {
                //为sql语句中？赋值
                preparedStatement.setObject(i + 1, params[i]);
            }
        return preparedStatement;
    }

    //通用的增删改
    public static boolean executeUpdate(String sql, Object[] params) throws SQLException {
        preparedStatement = createPreParedStatement(sql, params);
        int count = preparedStatement.executeUpdate();
        C3P0Util.closeAll(resultSet, preparedStatement, connection);
        if (count > 0) {
            return true;
        } else {
            return false;
        }
    }

    //通用的查询
    public static ResultSet executeQuery(String sql, Object[] params) throws SQLException {
        preparedStatement = createPreParedStatement(sql, params);
        ResultSet resultSet = preparedStatement.executeQuery();
        return resultSet;
    }

    //通用的查询总数
    public static int getTotalCount(String sql) throws SQLException {
        int count = -1;
        preparedStatement = createPreParedStatement(sql, null);
        resultSet = preparedStatement.executeQuery();
        if (resultSet.next()) {
            count = resultSet.getInt(1);
        }

        C3P0Util.closeAll(resultSet, preparedStatement, connection);
        return count;
    }

    public static void closeAll(ResultSet resultSet, PreparedStatement preparedStatement, Connection connection) {
        C3P0Util.closeAll(resultSet, preparedStatement, connection);
    }

}
